//
//  YLHomeViewController.m
//  YLFinanceService
//
//  Created by she1323 on 2017/8/23.
//  Copyright © 2017年 she1323. All rights reserved.
//  首页  3117 / 1531  33 66

#import "YLHomeViewController.h"
#import <MJRefresh.h>
#import "YLGoodsCollectionViewCell.h"
#import "YLGoodsViewModel.h"
#import "YLGlobeHeader.h"
#import "YLAdLineFooterView.h"
#import "YLSlideIamgeHeadView.h"
#import "YLProductCollectionCell.h"
#import "YLHomeGoodsHeaderView.h"
#import "ULBCollectionViewFlowLayout.h"
#import "YLHomeGoodsHeaderView.h"
#import "YLHomeButtonCollectionCell.h"
#import "YLHomeButtonViewModel.h"
#import "YLEndFooterView.h"
#import "YLMessageBaseViewController.h"
#import "YLHomeProductViewModel.h"
#import "WHProgressHUD.h"
#import "YLProductDetailController.h"
#import <MJRefresh.h>
#import "YLNavigationController.h"
#import "YLRealNameAuthenticationViewController.h"
#import "YLSignViewController.h"
#import "YLMemberController.h"
#import "YLAccountTool.h"
#import "YLCertifiedPaymentViewController.h"
#import "YLAdView.h"
#import "YLAdViewModel.h"
#import "YLAdModel.h"
#import "WHWebViewController.h"
#import "WHNetworkTool.h"
#import "SCSecureHelper.h"
@interface YLHomeViewController ()<UICollectionViewDelegateFlowLayout,ULBCollectionViewDelegateFlowLayout>
@property (nonatomic, strong) YLGoodsViewModel *goodsViewModel;

@property (nonatomic, strong) YLHomeButtonViewModel *buttonViewModel;

@property (nonatomic, strong) YLHomeProductViewModel *productViewModel;

@property (nonatomic, strong) NSString *showString;

@property (nonatomic, strong) YLAdViewModel *adViewModel;
@end

@implementation YLHomeViewController

- (YLAdViewModel *)adViewModel
{
    if (!_adViewModel) {
        _adViewModel = [[YLAdViewModel alloc] init];
        _adViewModel.conditionId = 11;
    }
    return _adViewModel;
}

// 仅设置当前页面
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [WHProgressHUD dismiss];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (YLGoodsViewModel *)goodsViewModel
{
    if (!_goodsViewModel) {
        _goodsViewModel = [[YLGoodsViewModel alloc] init];
    }
    return _goodsViewModel;
}

- (YLHomeButtonViewModel *)buttonViewModel
{
    if (!_buttonViewModel) {
        _buttonViewModel = [[YLHomeButtonViewModel alloc] init];
    }
    return _buttonViewModel;
}

- (YLHomeProductViewModel *)productViewModel
{
    if (!_productViewModel) {
        _productViewModel = [[YLHomeProductViewModel alloc] init];
    }
    return _productViewModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
//    NSString *url = [NSString stringWithFormat:@"%@Product/SetFundQualifications", YLURL];
//    
//    [[WHNetworkTool shareInstance] sendPostWithUrl:url header:[YLAccountTool header] params:@{@"Status" : @(0)} success:^(id responseObject) {
//        
//    } fail:^(NSError *error) {
//        
//    }];
     [self setUpCollectionView];
    
     __weak typeof(self) weakSelf = self;
     [[self.adViewModel.requestCommand execute:nil] subscribeNext:^(id  _Nullable x) {
        YLAdModel *model = x;
        YLAdView *adView = [[YLAdView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        adView.iconUrl = model.noticeIcon;
        [[UIApplication sharedApplication].keyWindow addSubview:adView];
        adView.clickBlock = ^{
            WHWebViewController *webCon = [[WHWebViewController alloc] init];
            [weakSelf.navigationController pushViewController:webCon animated:YES];
        };
    }];
    
    _showString = @"";
    
    self.view.backgroundColor = [UIColor whiteColor];
   
    [self.goodsViewModel.signSubject subscribeNext:^(id  _Nullable x) {
        
        if ([YLAccountTool account].authState == 1) {
            YLSignViewController *sign = [[YLSignViewController alloc] init];
            [weakSelf.navigationController pushViewController:sign animated:YES];
        } else {
            YLCertifiedPaymentViewController *realNameController = [[YLCertifiedPaymentViewController alloc] init];
            [weakSelf.navigationController pushViewController:realNameController animated:YES];
        }
 }];
    
    [self.goodsViewModel.memberCenterSubject subscribeNext:^(id  _Nullable x) {
        if ([YLAccountTool account].authState == 1) {
            YLMemberController *member = [[YLMemberController alloc] init];
            [weakSelf.navigationController pushViewController:member animated:YES];
        } else {
            YLCertifiedPaymentViewController *realNameController = [[YLCertifiedPaymentViewController alloc] init];
            [weakSelf.navigationController pushViewController:realNameController animated:YES];
        }
    }];
    
    [self.goodsViewModel.toProductSubject subscribeNext:^(id  _Nullable x) {
        [weakSelf.tabBarController setSelectedIndex:1];
    }];
}

- (void)setUpCollectionView
{
    self.collectionView.frame = CGRectMake(0, 0, YLScreenW, YLScreenH - 44);
    self.collectionView.alwaysBounceVertical = YES;
    self.collectionView.backgroundColor = YLBackGroundColor;
  
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([YLGoodsCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:[YLGoodsCollectionViewCell cellID]];
    [self.collectionView registerClass:[YLSlideIamgeHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[YLSlideIamgeHeadView headID]];
    [self.collectionView registerClass:[YLAdLineFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:[YLAdLineFooterView footerID]];
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([YLProductCollectionCell class]) bundle:nil] forCellWithReuseIdentifier:[YLProductCollectionCell cellID]];
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([YLHomeGoodsHeaderView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[YLHomeGoodsHeaderView headerID]];
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([YLHomeButtonCollectionCell class]) bundle:nil] forCellWithReuseIdentifier:[YLHomeButtonCollectionCell cellID]];
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([YLEndFooterView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:[YLEndFooterView footerID]];
    
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, self.tabBarController.tabBar.frame.size.height - 44, 0);
    
    __weak typeof(self) weakSelf = self;
    
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [[weakSelf.productViewModel.productCommand execute:nil] subscribeNext:^(id  _Nullable x) {
            [weakSelf.collectionView.mj_header endRefreshing];
            [weakSelf.collectionView reloadData];
        }];
    }];
    
    BOOL gestureOpen = [SCSecureHelper gestureOpenStatus];
    if (gestureOpen) {
        [self.collectionView.mj_header beginRefreshing];
    } else {
        [WHProgressHUD showStatus:@"正在加载首页数据..."];
        [[self.productViewModel.productCommand execute:nil] subscribeNext:^(id  _Nullable x) {
            [WHProgressHUD dismiss];
            [weakSelf.collectionView reloadData];
        }];
    }

    [self.productViewModel.wh_loadDataErrorSubject subscribeNext:^(id  _Nullable x) {
        [weakSelf setEmpty];
        [WHProgressHUD dismiss];
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView reloadData];
    }];
    
    if (@available(iOS 11.0, *)) {
        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (instancetype)init
{
    ULBCollectionViewFlowLayout *layout = [[ULBCollectionViewFlowLayout alloc] init];
    return [self initWithCollectionViewLayout:layout];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    if (self.productViewModel.groups.count == 0) {
        return 0;
    }
    return self.productViewModel.groups.count + 2;
}

- (UIColor *)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout colorForSectionAtIndex:(NSInteger)section
{
    if (section == 0) {
        return [UIColor whiteColor];
    } else {
        return YLBackGroundColor;
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (section == 0) {
        return self.goodsViewModel.goods.count;
    } else if (section == self.productViewModel.groups.count + 1) {
        return self.buttonViewModel.buttons.count;
    }
    
    YLHomeProductGroup *group = self.productViewModel.groups[section - 1];
    return group.productList.items.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = nil;
    if (indexPath.section == 0) {
        YLGoodsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[YLGoodsCollectionViewCell cellID] forIndexPath:indexPath];
        cell.model = self.goodsViewModel.goods[indexPath.row];
        return cell;
        
    } else if(indexPath.section == self.productViewModel.groups.count + 1) {
        YLHomeButtonCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[YLHomeButtonCollectionCell cellID] forIndexPath:indexPath];
        cell.model = self.buttonViewModel.buttons[indexPath.row];
        return cell;
    }
    else {
        YLProductCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[YLProductCollectionCell cellID] forIndexPath:indexPath];
        YLHomeProductGroup *group = self.productViewModel.groups[indexPath.section - 1];
        YLProductModel *model = group.productList.items[indexPath.row];
        cell.model = model;
        return cell;
    }
    return cell;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (section == 0) {
        return UIEdgeInsetsMake(20, 10, 10, 10);
    } else if (section == self.productViewModel.groups.count + 1) {
        return UIEdgeInsetsMake(20, (YLScreenW - (YLScreenW / 4.0 * 3)) / 4.0, 10, (YLScreenW - (YLScreenW / 4.0 * 3)) / 4.0);
    }
    return UIEdgeInsetsZero;
}

#pragma mark <UICollectionViewDelegate>

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return CGSizeMake(YLScreenW / 5, YLScreenW / 5.2);
    } else if (indexPath.section == self.productViewModel.groups.count + 1) {
        return CGSizeMake(YLScreenW / 4.0, YLScreenW / 4.0 * 105 / 210);
    }
    return CGSizeMake(YLScreenW, 110);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0.001;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self) weakSelf = self;
    UICollectionReusableView *resuableView = nil;
    
    if (kind == UICollectionElementKindSectionHeader) {
        if (indexPath.section == 0) {
            YLSlideIamgeHeadView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:[YLSlideIamgeHeadView headID] forIndexPath:indexPath];
            resuableView = headerView;
        } else if (indexPath.section == self.productViewModel.groups.count + 1){
        }
        
        else {
            YLHomeGoodsHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:[YLHomeGoodsHeaderView headerID] forIndexPath:indexPath];
            headerView.group = self.productViewModel.groups[indexPath.section - 1];
        
            resuableView = headerView;
        }
    } else {
        if (indexPath.section == 0) {
            YLAdLineFooterView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:[YLAdLineFooterView footerID] forIndexPath:indexPath];
            footerView.clickBlock = ^{
                YLMessageBaseViewController *notice = [[YLMessageBaseViewController alloc] init];
                notice.messageType = YLMessageTypeAnnouncement;
                [weakSelf.navigationController pushViewController:notice animated:YES];
            };
            resuableView = footerView;
            
        } else if (indexPath.section == self.productViewModel.groups.count + 1) {
            YLEndFooterView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:[YLEndFooterView footerID] forIndexPath:indexPath];
            resuableView = footerView;
        }
    }
    
    if (resuableView == nil) {
        resuableView = [[UICollectionReusableView alloc] init];
    }
    
    return resuableView;
}

#pragma mark - head宽高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return CGSizeMake(YLScreenW, YLScreenW * 9 / 16.0); //图片滚动的宽高
    } else if (section == self.productViewModel.groups.count + 1) {
        return CGSizeZero;
    }
   
    return CGSizeMake(YLScreenW / 4.0, 60);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return CGSizeMake(YLScreenW, 30);
    } else if (section == self.productViewModel.groups.count + 1) {
        return CGSizeMake(YLScreenW, 30);
    }
    return CGSizeZero;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        YLGoodsModel *model = self.goodsViewModel.goods[indexPath.row];
        if (model.clickBlock) {
            NSString *name = model.clickBlock();
            if (name.length > 0) {
                [self.navigationController pushViewController:[[NSClassFromString(name) alloc] init] animated:YES];
            }
        }
    } else if (indexPath.section == self.productViewModel.groups.count + 1) {
       YLHomeButtonModel *buttonModel =  _buttonViewModel.buttons[indexPath.row];
        if (buttonModel.buttonClickBlcok) {
            NSString *className = buttonModel.buttonClickBlcok();
            if (className.length > 0) {
               UIViewController *v = [[NSClassFromString(className) alloc] init];
                [self.navigationController pushViewController:v animated:YES];
            }
        }
    }   else {
        
        YLHomeProductGroup *group = self.productViewModel.groups[indexPath.section - 1];
        YLProductModel *model = group.productList.items[indexPath.row];
        YLProductDetailController *detail = [[YLProductDetailController alloc] init];
        detail.model = model;
        [self.navigationController pushViewController:detail animated:YES];
}
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString * text = @"点击重新加载";
    
    NSDictionary * attributes = @ { NSFontAttributeName:[UIFont boldSystemFontOfSize:14.0f ],
        NSForegroundColorAttributeName:YLLineColor};
    
    return [[ NSAttributedString  alloc ] initWithString:text attributes:attributes];
}

// 处理空白区域的点击事件
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view
{
    __weak typeof(self) weakSelf = self;
    [[self.productViewModel.productCommand execute:nil] subscribeNext:^(id  _Nullable x) {
        [weakSelf.collectionView reloadData];
    }];
}

- (CGFloat)spaceHeightForEmptyDataSet:(UIScrollView *)scrollView
{
    return 25.0f;
}


@end
